/*
 * Copyright 2007-2008 Andrew O'Malley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package ws.quokka.plugin.jar;

import org.apache.tools.ant.taskdefs.Jar;
import org.apache.tools.ant.types.Path;

import ws.quokka.core.metadata.Metadata;
import ws.quokka.core.metadata.MetadataAware;
import ws.quokka.core.plugin_spi.support.Setter;
import ws.quokka.core.plugin_spi.support.TypedProperties;
import ws.quokka.core.repo_spi.RepoArtifactId;
import ws.quokka.core.util.Strings;

import ws.quokka.plugin.lifecycle.LifeCycleImpl;

import java.io.File;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


/**
 * JarPlugin packages artifacts of type "jar". It supports multiple artifacts
 */
public class JarPlugin extends LifeCycleImpl implements MetadataAware {
    //~ Instance fields ------------------------------------------------------------------------------------------------

    private Metadata metadata;

    //~ Methods --------------------------------------------------------------------------------------------------------

    public void setMetadata(Metadata metadata) {
        this.metadata = metadata;
    }

    public void jarTemplate() {
        // Get supported types
        List types = new ArrayList();
        types.addAll(Arrays.asList(new String[] { "jar", "archetype", "plugin", "depset" })); // Built-ins
        types.addAll(Strings.commaSepList(properties().getString("additionalTypes", null))); // Additional

        // Get the specific artifact, if specified
        String[] tokens = Strings.split(properties().getString("artifact", null));
        String name = (tokens != null) ? tokens[0] : null;
        String type = (tokens != null) ? ((tokens.length > 1) ? tokens[1] : "jar") : null;

        // Find the matching artifact
        List artifacts = metadata.getArtifactIds(types);
        assertTrue((artifacts.size() <= 1) || (name != null),
            "You must create a separate target for each artifact and set the 'artifact' property to <name>[:type]");

        RepoArtifactId packageId = null;

        if (name == null) {
            packageId = (artifacts.size() == 1) ? (RepoArtifactId)artifacts.get(0) : null;
        } else {
            for (Iterator i = artifacts.iterator(); i.hasNext();) {
                RepoArtifactId id = (RepoArtifactId)i.next();

                if (id.getName().equals(name) && id.getType().equals(type)) {
                    packageId = id;

                    break;
                }
            }
        }

        if (packageId != null) {
            doPackage(packageId);
        }
    }

    private void doPackage(RepoArtifactId id) {
        utils().mkdir(getLifeCycle().getPackageOutput());

        TypedProperties properties = properties();
        Setter setter = new Setter(properties);
        Jar jar = (Jar)getProject().createTask("jar");
        jar.setDestFile(getPackageFile(id));
        jar.addFileset(properties.getFileSet("source"));

        setter.set(jar,
            new String[] {
                "compress", "keepCompression", "encoding", "filesOnly", "defaultExcludes", "manifest", "filesetManifest",
                "update", "whenManifestOnly", "duplicate", "index", "manifestEncoding", "roundUp", "level"
            });

        Path path = properties.getPath("indexJars", null);

        if (path != null) {
            jar.addConfiguredIndexJars(path);
        }

        // TODO: add remaining attributes ... for now
        //        jar.addConfiguredService();
        //        jar.addMetainf();
        //        jar.addConfiguredManifest();
        jar.perform();
    }

    private File getPackageFile(RepoArtifactId id) {
        return new File(getLifeCycle().getPackageOutput(), id.toPathString() + ".jar");
    }
}
